package com.demo.demoproject.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.demo.demoproject.domain.Result;
import com.demo.demoproject.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        String jwt = request.getHeader("token");

        // 判断url是否为空
        if (!StringUtils.hasLength(url)) {
            sendResponse(response, HttpServletResponse.SC_NOT_FOUND, "NOT_FOUND");
            return false;
        }

        // 检验令牌是否存在
        if (!StringUtils.hasLength(jwt)) {
            sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "NOT_LOGIN");
            return false;
        }

        // 解析token
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            // 使用日志记录异常信息
            log.error("Token parsing error: {}", e.getMessage(), e);
            sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "NOT_LOGIN");
            return false;
        }

        return true;
    }

    /**
     * 发送响应
     * @param response 响应对象
     * @param statusCode 状态码
     * @param message 消息
     * @throws IOException 异常
     */
    private void sendResponse(@NotNull HttpServletResponse response, int statusCode, String message) throws IOException {
        response.setStatus(statusCode);
        Result result = Result.fail(message);
        String jsonResponse = JSONObject.toJSONString(result);
        response.getWriter().write(jsonResponse);
    }
}
